<?php
	
	// Cargamos CI
	define('CI_INDEX', realpath('../../../../../../index.php'));   // Your CodeIgniter main index.php file  
	  
	chdir(dirname(CI_INDEX));	
	ob_start();
		include(CI_INDEX);
		$CI =& get_instance();
	ob_end_clean();
	
	// Comprobamos permisos necesarios
	$CI->load->library("redux_auth");	
	
	if(!$CI->redux_auth->logged_in()){
		die("{ result: false, message: 'No estas logado'}");
	}
	
	$profile = $CI->redux_auth->profile();
	if($profile->group != "admin"){
		die("{ result: false, message: 'No tienes el rol apropiado'}");
	}
		
	
	/*** Comenzamos el script ***/
	$uploadok = false;
	
	if(isset($_FILES['userfile'])){

		$ROOT_RELATIVE_PATH = "./";
		if(isset($_REQUEST['upload_path']) && $_REQUEST['upload_path'] != ""){
			$ROOT_UPLOAD_PATH = $_REQUEST['upload_path'];
		} else{
			$ROOT_UPLOAD_PATH = "contents/tmp/";
		}
		
		if(!file_exists($ROOT_RELATIVE_PATH.$ROOT_UPLOAD_PATH)){
			mkdir($ROOT_RELATIVE_PATH.$ROOT_UPLOAD_PATH);
			chmod($ROOT_RELATIVE_PATH.$ROOT_UPLOAD_PATH, 0777);
		}
		
		//@TODO problema con realpath
		$UPLOAD_PATH = realpath($ROOT_RELATIVE_PATH . $ROOT_UPLOAD_PATH);
			
		if(substr($UPLOAD_PATH, strlen($UPLOAD_PATH) - strlen("\\")) != "\\"){
			$UPLOAD_PATH = $UPLOAD_PATH . "\\";
		}
		
		$UPLOAD_PATH = str_replace("\\", "/", $UPLOAD_PATH);	
		
		
		
		//$uploadfilename = time() . "_" . basename($_FILES['userfile']['name']);
		$pathinfo = pathinfo($_FILES['userfile']['name']);
		$uploadfilename = $pathinfo['filename'] . "_" . time() . "." . $pathinfo['extension'];
		$uploadrelativefilepath = $ROOT_UPLOAD_PATH . $uploadfilename;
		$uploadfilepath = $UPLOAD_PATH . $uploadfilename;
		
		
		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfilepath)) {
			chmod($uploadfilepath, 0777);
			$uploadok = true;
		}
	}
	
?>

<?php if($uploadok):?>
{
	result: true,
	
	filename: "<?php echo $uploadfilename?>",
	filerelativepath: "<?php echo $uploadrelativefilepath?>",
	filepath: "<?php echo $uploadfilepath?>"
}
<?php else:?>
{
	result: false
}
<?php endif;?>